package cn.stylefeng.guns.modular.fsjs.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ExcellUtil;
import cn.stylefeng.guns.core.util.ServerResponse;
import cn.stylefeng.guns.modular.system.model.Halfusewater;
import cn.stylefeng.guns.modular.system.model.Indenteruwy;
import cn.stylefeng.guns.modular.system.model.Swyreport;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.dao.BasemsgMapper;
import cn.stylefeng.guns.modular.system.dao.IndenteruwyMapper;
import cn.stylefeng.guns.modular.system.dao.SwyreportMapper;
import cn.stylefeng.guns.modular.fsjs.service.IIndenteruwyService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2019-03-06
 */
@Service
public class IndenteruwyServiceImpl extends ServiceImpl<IndenteruwyMapper, Indenteruwy> implements IIndenteruwyService {
	String mainPath="";
	@Autowired
	private IndenteruwyMapper indenteruwyMapper;
	@Autowired
    private IUserService userService;
	@Override
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=Exception.class,isolation = Isolation.READ_COMMITTED)
	public Object pushMsg(HttpServletRequest request, List<Indenteruwy> indenteruwyLi) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		User user = userService.selectById(ShiroKit.getUser().getId());
    	if(indenteruwyMapper.getIfComit(user)>0){
			return ServerResponse.createByErrorMessage("年报数据已经提交，无法修改");
		}
    	mainPath=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\";
    	int point=0;
    	for(int i=0;i<indenteruwyLi.size();i++){
			Indenteruwy temp=indenteruwyLi.get(i);
			if(this.checkInput(temp, i)==false){
				return ServerResponse.createByErrorMessage("提交数据有误");
			}
    	}
		for(int i=0;i<indenteruwyLi.size();i++){
			Indenteruwy temp=indenteruwyLi.get(i);
			if(this.checkInput(temp, i)==true){
				temp.setTs(sf.format(new Date()));
				temp.setAccount(user.getAccount());
				temp.setOperater(user.getAccount());
				temp.setPrjType((i+1)+"");
				temp.setVersion("2");
			}else{
				continue;
			}
			if(i==0){
				indenteruwyMapper.delTempMsg(temp);
			}
			
			if(indenteruwyMapper.pushMsg(temp)==0){
				return ServerResponse.createByErrorMessage("保存数据库出错");
			}else if(i==0){
				point++;
			}
			
		}
//			this.delMsg(user);
			if(point>0){
				//初始化excell成功
				Indenteruwy temp=indenteruwyLi.get(0);
				temp.setAccount(user.getAccount());
				ServerResponse cf=(ServerResponse)this.createFile(temp);
				if(cf.getCode()==200){
					//
					List<Indenteruwy> bsg=this.getMsgByAccountExcell(temp);
					if(bsg.size()>0){
						
						ServerResponse sm=(ServerResponse)this.stuffMsg(bsg,user);
						if(sm.getCode()==200){
							ServerResponse fn=(ServerResponse)this.toPDF(temp);
							if(fn.getCode()==200){
								this.delMsg(user);
								return ServerResponse.createBySuccessMessage("保存成功");
							}else{
								return fn;
							}
						}else{
							return sm;
						}
						
					}else{
						return ServerResponse.createByErrorMessage("数据库不存在记录");
					}
					
				}else{
					return cf;
				}
				
			}else{
				return ServerResponse.createByErrorMessage("数据格式错误");
			}
		
	}

	public boolean checkInput(Indenteruwy temp,int i){
		if(i>0||
		   (temp.getRecYear()!=null&&
	//				   StringUtils.isNotBlank(temp.getPrjType())&&
		   temp.getIndustrySum()!=null&&
		   temp.getRecycleSum()!=null&&
		   temp.getRecycleUseRate()!=null&&
		   temp.getIndSumValue()!=null&&
		   temp.getWaterIntake()!=null&&
		   StringUtils.isNotBlank(temp.getProduct())&&
		   temp.getOutput()!=null&&
		   StringUtils.isNotBlank(temp.getUnitName())&&
		   temp.getWaterGetSum()!=null&&
		   temp.getTrapWater()!=null&&
		   temp.getSurfaceWater()!=null&&
		   temp.getGroundWater()!=null&&
		   temp.getQuotaWater()!=null&&
		   temp.getUserWater()!=null)
		   
		   
		   /* !"".equals(temp.getProduct().trim())||
		   !"".equals(temp.getUnitName().trim())||
		   temp.getWSUtensil()!=null||
		   temp.getCoolWater()!=null||
		   temp.getTechWater()!=null||
		   temp.getBoilerWater()!=null||
		   temp.getLiveWater()!=null||
		   temp.getCoolRecycleWater()!=null||
		   temp.getTechRecycleWater()!=null||
		   temp.getBoilerRecycleWater()!=null||
		   temp.getUnusuaeWater()!=null||
		   temp.getOtherWater()!=null*/
		   
				){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	public List<Indenteruwy> getMsgByAccount(User user) {
		return  indenteruwyMapper.getMsgByAccount(user);
	}

	@Override
	public List<Map<String, String>> getHangyeCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Indenteruwy> getMsgByAccountExcell(Indenteruwy indenteruwy) {
		
		/*File file=new File(mainPath+swyreport.getAccount()+"_用水单位基本信息.xlsx");
		 FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			Workbook workbook= WorkbookFactory.create(fis);
			Sheet sheet=workbook.getSheetAt(0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return indenteruwyMapper.getMsgByAccountExcell(indenteruwy);
	}

	
	
	private Object createFile(Indenteruwy indenteruwy){
		return ExcellUtil.copyFile(mainPath,indenteruwy,"工业企业用水情况年报表");
	}
	
	private Object stuffMsg(List<Indenteruwy> indenteruwyLi,User user){
//		ExcellUtil.insertRows(mainPath+swyreport.getAccount()+"_中水.xlsx", 12,30,16);
		File file=new File(mainPath+indenteruwyLi.get(0).getAccount()+"_工业企业用水情况年报表.xlsx");
		try {
		FileInputStream fis=new FileInputStream(file);
	     Workbook workbook= WorkbookFactory.create(fis);
	     Sheet sheet=workbook.getSheetAt(0);
	   //填表单位名称
	     if(user.getCompany()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,0,5);
	    	 oldValue=oldValue.replace("：", "："+user.getCompany());
	    	 ExcellUtil.updateExcel(sheet,0,5,oldValue);
	     }
	   //年份
	     if(indenteruwyLi.get(0).getRecYear()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,4,5);
	    	 oldValue=oldValue.replace("20  ", Integer.toString(indenteruwyLi.get(0).getRecYear()));
	    	 ExcellUtil.updateExcel(sheet,4,5,oldValue);
	     }
	     
	   //报出日期
		 if(indenteruwyLi.get(0).getTs()!=null){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,27);
			 String preValue="";
			 for(int c=0;c<indenteruwyLi.get(0).getTs().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("报出日期："+preValue, "报出日期："+indenteruwyLi.get(0).getTs().substring(0, 10));
			 ExcellUtil.updateExcel(sheet,0,27,oldValue);
		 }
	   //单位负责人:
		 if(indenteruwyLi.get(0).getUnitHead()!=null){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,27);
			 String preValue="";
			 for(int c=0;c<indenteruwyLi.get(0).getUnitHead().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("单位负责人："+preValue, "单位负责人："+indenteruwyLi.get(0).getUnitHead());
			 ExcellUtil.updateExcel(sheet,0,27,oldValue);
		 }
		//填表人
		 if(indenteruwyLi.get(0).getOperater()!=null){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,27);
			 String preValue="";
			 for(int c=0;c<indenteruwyLi.get(0).getOperater().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("填表人："+preValue, "填表人："+indenteruwyLi.get(0).getOperater());
			 ExcellUtil.updateExcel(sheet,0,27,oldValue);
		 }
		//电话
		 if(user.getPhone()!=null){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,27);
			 String preValue="";
			 for(int c=0;c<user.getPhone().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("联系电话："+preValue, "联系电话："+user.getPhone());
			 ExcellUtil.updateExcel(sheet,0,27,oldValue);
		 }
		
	     
	     
		for(int i=0;i<indenteruwyLi.size();i++){
			Indenteruwy tmp=indenteruwyLi.get(i);
			//工业用水总量
			if(tmp.getIndustrySum()!=null){
				ExcellUtil.updateExcel(sheet,2,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getIndustrySum()));
			}
			//重复用水总量
			if(tmp.getRecycleSum()!=null){
				ExcellUtil.updateExcel(sheet,7,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getRecycleSum()));
			}
			//工业用水重复利用率
			if(tmp.getRecycleUseRate()!=null){
				ExcellUtil.updateExcel(sheet,13,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getRecycleUseRate()));
			}
			//工业总产值
			if(tmp.getWaterIntake()!=null){
				ExcellUtil.updateExcel(sheet,14,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getWaterIntake()));
			}
			
			//主要产品名称
			if(tmp.getProduct()!=null){
				ExcellUtil.updateExcel(sheet,2,17+Integer.parseInt(tmp.getPrjType()),tmp.getProduct());
			}
			
			//本年度产量
			if(tmp.getOutput()!=null){
				ExcellUtil.updateExcel(sheet,5,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getOutput()));
			}
			//单位
			if(tmp.getUnitName()!=null){
				ExcellUtil.updateExcel(sheet,7,17+Integer.parseInt(tmp.getPrjType()),tmp.getUnitName());
			}
			//本年度取水总量
			if(tmp.getWaterGetSum()!=null){
				ExcellUtil.updateExcel(sheet,8,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getWaterGetSum()));
			}
			//市政供水
			if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,9,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getTrapWater()));
			}
			//地表水
			if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,10,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getSurfaceWater()));
			}
			//地下水
			if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,11,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getGroundWater()));
			}
			//产品单位定额
			if(tmp.getQuotaWater()!=null){
				ExcellUtil.updateExcel(sheet,12,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getQuotaWater()));
			}
			//产品单位取水量
			if(tmp.getUserWater()!=null){
				ExcellUtil.updateExcel(sheet,13,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getUserWater()));
			}
			//非节水器具
			if(tmp.getUtensil()!=null){
				ExcellUtil.updateExcel(sheet,15,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getUtensil()));
			}
			//节水器具
			if(tmp.getWSUtensil()!=null){
				ExcellUtil.updateExcel(sheet,14,17+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getWSUtensil()));
			}
			//间接冷却水
			if(tmp.getCoolWater()!=null){
				ExcellUtil.updateExcel(sheet,3,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getCoolWater()));
			}
			//工艺取水
			if(tmp.getTechWater()!=null){
				ExcellUtil.updateExcel(sheet,4,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getTechWater()));
			}
			//锅炉取水
			if(tmp.getBoilerWater()!=null){
				ExcellUtil.updateExcel(sheet,5,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getBoilerWater()));
			}
			//生活取水
			if(tmp.getLiveWater()!=null){
				ExcellUtil.updateExcel(sheet,6,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getLiveWater()));
			}
			//间接冷却循环水
			if(tmp.getCoolRecycleWater()!=null){
				ExcellUtil.updateExcel(sheet,8,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getCoolRecycleWater()));
			}
			//工艺回用量
			if(tmp.getTechRecycleWater()!=null){
				ExcellUtil.updateExcel(sheet,9,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getTechRecycleWater()));
			}
			//锅炉冷凝水回用量
			if(tmp.getBoilerRecycleWater()!=null){
				ExcellUtil.updateExcel(sheet,10,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getBoilerRecycleWater()));
			}
			//非常规水回用量
			if(tmp.getUnusuaeWater()!=null){
				ExcellUtil.updateExcel(sheet,11,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getUnusuaeWater()));
			}
			//其他
			if(tmp.getOtherWater()!=null){
				ExcellUtil.updateExcel(sheet,12,9+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getOtherWater()));
			}
		}
		fis.close();//关闭文件输入流
		 
	     FileOutputStream fos=new FileOutputStream(file);
	     workbook.write(fos);
	     fos.close();//关闭文件输出流
		 
		 return ServerResponse.createBySuccessMessage("填充数据成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ServerResponse.createBySuccessMessage("修改excell成功");
	}
	
	private Object toPDF(Indenteruwy indenteruwy){
		try {
			return ExcellUtil.excel2Pdf(mainPath,indenteruwy,"工业企业用水情况年报表");
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage(e.getMessage());
		}
	}
	
	private void delMsg(User user){
		indenteruwyMapper.delMsg(user);
		indenteruwyMapper.updateVersion(user);
	}
	
	@Override
	public Object checkCommit(User user) {
		List<Indenteruwy> indenteruwyLi=this.getMsgByAccount(user);
		if(indenteruwyLi.size()>0){
			for(int i=0;i<indenteruwyLi.size();i++){
				Indenteruwy temp=indenteruwyLi.get(i);
				if(i==0&&
						(temp.getRecYear()==null||
						StringUtils.isBlank(temp.getPrjType())||
						temp.getIndustrySum()==null||
						temp.getRecycleSum()==null||
						temp.getRecycleUseRate()==null||
						temp.getIndSumValue()==null||
						temp.getWaterIntake()==null||
						StringUtils.isBlank(temp.getProduct())||
						temp.getOutput()==null||
						StringUtils.isBlank(temp.getUnitName())||
						temp.getWaterGetSum()==null||
						temp.getTrapWater()==null||
						temp.getSurfaceWater()==null||
						temp.getGroundWater()==null||
						temp.getQuotaWater()==null||
						temp.getUserWater()==null)
						
						/*temp.getPrjType()==null||
				temp.getIndustrySum()==null||
				temp.getRecycleSum()==null||
				temp.getRecycleUseRate()==null||
				temp.getIndSumValue()==null||
				temp.getWaterIntake()==null||
				"".equals(temp.getProduct().trim())||
				temp.getOutput()==null||
				"".equals(temp.getUnitName().trim())||
				temp.getWaterGetSum()==null||
				temp.getTrapWater()==null||
				temp.getSurfaceWater()==null||
				temp.getGroundWater()==null||
				temp.getQuotaWater()==null||
				temp.getUserWater()==null||
				temp.getUtensil()==null||
				temp.getWSUtensil()==null||
				
				temp.getCoolWater()==null||
				temp.getTechWater()==null||
				temp.getBoilerWater()==null||
				temp.getLiveWater()==null||
				temp.getCoolRecycleWater()==null||
				temp.getTechRecycleWater()==null||
				temp.getBoilerRecycleWater()==null||
				temp.getUnusuaeWater()==null||
				temp.getOtherWater()==null*/
						){
					return ServerResponse.createByErrorMessage("工业企业用水情况年报表内容尚未填写完成");
				}
			}
			return ServerResponse.createBySuccessMessage("工业企业用水情况年报表内容填写完成");
		}else{
			return ServerResponse.createByErrorMessage("工业企业用水情况年报表内容尚未填写完成");
		}
	}
	
	@Override
	public int getIfComit(User user) {
		return indenteruwyMapper.getIfComit(user);
	}

	@Override
	public int updateComit() {
		return indenteruwyMapper.updateComit();
	}

	@Override
	public Object bulidEmptyFile(String path, Indenteruwy indenteruwy, User user) {
		mainPath=path;
		List<Indenteruwy> temp=new ArrayList<Indenteruwy>();
		temp.add(indenteruwy);
		//初始化excell成功
		ServerResponse cf=(ServerResponse)this.createFile(indenteruwy);
		if(cf.getCode()==200){
			//
			ServerResponse sm=(ServerResponse)this.stuffMsg(temp,user);
			if(sm.getCode()==200){
				ServerResponse fn=(ServerResponse)this.toPDF(indenteruwy);
					if(fn.getCode()==200){
						return ServerResponse.createBySuccessMessage("保存成功");
					}else{
						return fn;
					}
			}else{
				return sm;
			}
			
			}else{
				return ServerResponse.createByErrorMessage("数据库不存在记录");
			}
	}
}
